//
//  CZEmoticonKeyBoard.swift
//  WHWeiBo01
//
//  Created by whitcast on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//  重用标记
private let CZEmoticonCollectionViewCellIdentifier = "CZEmoticonCollectionViewCellIdentifier"

//  表情键盘
class CZEmoticonKeyBoard: UIView {
    // MARK:    --懒加载控件
    private lazy var toolBar: CZEmoticonToolBar = {
        let view = CZEmoticonToolBar(frame: CGRectZero)
        return view
    
    }()
    
    //  表情视图
    private lazy var emoticonCollectionView: UICollectionView = {
        //  布局方式
        let flowLayout = UICollectionViewFlowLayout()
        //  设置水平方向滚动
        flowLayout.scrollDirection = .Horizontal
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        //  去掉水平方向和垂直方向的滚动指示条
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        //  开启分页模式
        view.pagingEnabled = true
        //  去掉弹簧效果
        view.bounces = false
        
        view.backgroundColor = self.backgroundColor
        //  注册cell
        view.registerClass(CZEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: CZEmoticonCollectionViewCellIdentifier)
        //  设置数据源代理
        view.dataSource = self
        //  指定代理对象
        view.delegate = self
        return view
    
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    
    private func setupUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        addSubview(emoticonCollectionView)
        addSubview(toolBar)
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.bottom.equalTo(self)
            make.trailing.equalTo(self)
            
            make.height.equalTo(30)            
            
            
        }
        //  设置闭包
        toolBar.selectedToolBarButtonClosure = { [weak self] (type: CZEmoticonToolBarButtonType) in
            
            //  定义一个将要滚动到的一个NSIndexPath
            let indexPath: NSIndexPath
            switch type {
            case .Normal:
                print("normal")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Emoji:
                print("emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .Lxh:
                print("lxh")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            }
            
            //  滚动到指定indexPath,不需要动画 animated: false
            self?.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        }
        
        
        
        
        
        
    }
    
    //  重写layoutSubviews,获取子控件的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //  获取表情视图的布局方式
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  每项的大小等于我们表情视图的大小
        flowLayout.itemSize = emoticonCollectionView.size
        //  设置水平间距
        flowLayout.minimumInteritemSpacing = 0
        //  设置垂直间距
        flowLayout.minimumLineSpacing = 0
        
    }
    
    

}


extension CZEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonTools.shareTools.allEmoticonArray.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonTools.shareTools.allEmoticonArray[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZEmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! CZEmoticonCollectionViewCell
        
        cell.indexPath = indexPath
        //  设置模型
        cell.emoticons = CZEmoticonTools.shareTools.allEmoticonArray[indexPath.section][indexPath.item]
        return cell
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
//        print(scrollView.contentOffset.x)
        
        //  1. 获取屏幕显示的cell , 只是能够返回当前显示cell,但是不会给我通过frame.x进行排序
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            //  通过sort进行x坐标从小到大的排序
            return firstCell.x < secondCell.x
        }
       
        //  2. 判断哪个cell显示的多
        if cells.count == 2 {
            //  第一个cell
            let firstCell = cells.first!
            //  第二个cell
            let secondCell = cells.last!
            
            //  计算第一个cell的x坐标与水平偏移量的差值
            let firstCellContentOffSetX = abs(firstCell.x - scrollView.contentOffset.x)
            //  计算第二个cell的x坐标与水平偏移量的差值
            let secondCellContentOffSetX = secondCell.x - scrollView.contentOffset.x
//            print(firstCellContentOffSetX)
//            print(secondCellContentOffSetX)
            //  比较差值,通过规律可以得知,哪个差值小,哪个cell显示就越多
            let cell: UICollectionViewCell
            if firstCellContentOffSetX < secondCellContentOffSetX {
//                 print("第一个cell显示多")
                cell = firstCell
            } else {
//                print("第二个cell显示多")
                cell = secondCell
            }
            
            // 3. 通过cell获取对应的indexPath
            
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            
            // 4. 通过indexPath获取对应这个section
            let section = indexPath.section
            // 5. toolbar根据section让其指定的按钮选中
            toolBar.selectedButtonWidthSection(section)
        }
       
        
    }
    
    

}













